<template>
	<div>
		<a-form
			:wrapper-col="{ span: 16 }"
			:label-col="{ span: 8 }"
			autocomplete="off"
			labelAlign="right"
			ref="formRef"
			:model="formData"
			:rules="formRules"
		>
			<a-row>
				<a-col :span="12">
					<a-form-item label="销售方式" name="saleMethod">
						<a-select
							:disabled="props.disabled"
							placeholder="请选择销售方式"
							:options="tool.dictList('saleMethod')"
							v-model:value="formData.saleMethod"
						>
						</a-select>
					</a-form-item>
				</a-col>
				<a-col :span="12">
					<a-form-item label="销售合同" name="contractId">
						<xn-page-selector
							ref="revenueContractRef"
							:disabled="props.disabled"
							@change="onContractChange"
							:page-function="
								(param) =>
									revenueContractApi.page(
										Object.assign(param, {
											subType: 2,
											status: 1,
											type: 1
										})
									)
							"
							v-model:value="formData.contractId"
							placeholder="请选择销售合同"
						>
						</xn-page-selector>
					</a-form-item>
				</a-col>
			</a-row>
			<a-row>
				<a-col :span="12">
					<a-form-item label="销售员" name="salePerName">
						<div @click="selectionParticipants()">
							<a-input
								:disabled="props.disabled"
								readonly
								v-model:value="formData.salePerName"
								placeholder="请选择销售员"
								allow-clear
							/>
						</div>
					</a-form-item>
				</a-col>
				<a-col :span="12">
					<a-form-item label="客户名称" name="customerId">
						<xn-page-selector
							:disabled="props.disabled"
							ref="customerRef"
							:field-names="{ label: 'custName', value: 'id' }"
							:page-function="(param) => customerApi.getPage(param)"
							v-model:value="formData.customerId"
							placeholder="请选择客户名称"
						>
						</xn-page-selector>
					</a-form-item>
				</a-col>
			</a-row>
			<a-row>
				<a-col :span="12">
					<a-form-item label="结算方式" name="settleMethod">
						<a-select
							:disabled="props.disabled"
							:options="tool.dictList('payType')"
							v-model:value="formData.settleMethod"
							placeholder="请选择结算方式"
						>
						</a-select>
					</a-form-item>
				</a-col>
				<a-col :span="12">
					<a-form-item label="备注" name="remark">
						<a-input :disabled="props.disabled" v-model:value="formData.remark" placeholder="请输入备注" allow-clear />
					</a-form-item>
				</a-col>
			</a-row>
			<a-row>
				<a-col :span="24">
					<a-row>
						<a-col v-if="props.disabled">
							<a-button class="childAddButton"> 商品明细 </a-button>
						</a-col>
						<a-col v-else>
							<a-button type="primary" class="childAddButton" @click="addProduct()">
								<PlusOutlined />
								新增
							</a-button>
							<a-popconfirm title="是否删除?" @confirm="removeGoods()">
								<a-button style="margin-left: 12px" type="remove" danger>
									<LineOutlined />
									删除
								</a-button>
							</a-popconfirm>
						</a-col>
					</a-row>
					<a-table
						:row-selection="options.rowSelection"
						:pagination="false"
						:columns="goodsColumns"
						:data-source="formData.saleOrderDetailAddParamList"
						:scroll="{ x: 1000 }"
					>
						<template #headerCell="{ column }">
							<template v-if="column.dataIndex === 'warehouseId'">
								<span style="color: red">{{ column.title }}</span>
							</template>
						</template>
						<template #bodyCell="{ index, record, column }">
							<template v-if="column.dataIndex === 'index'">
								<span>{{ index + 1 }}</span>
							</template>

							<template v-if="column.dataIndex === 'saleNum'">
								<a-input
									:disabled="props.disabled"
									@input="orderNumChange(record)"
									:style="{ width: column.width }"
									v-model:value="record.saleNum"
								/>
							</template>

							<template v-if="column.dataIndex === 'taxPrice'">
								<a-input
									:disabled="props.disabled"
									@input="taxChange(record)"
									:style="{ width: column.width }"
									v-model:value="record.taxPrice"
								/>
							</template>

							<template v-if="column.dataIndex === 'noTaxPrice'">
								<a-input
									:disabled="props.disabled"
									@input="excludingTaxChange(record)"
									:style="{ width: column.width }"
									v-model:value="record.noTaxPrice"
								/>
							</template>

							<template v-if="column.dataIndex === 'warehouseId'">
								<a-select
									:getPopupContainer="(trigger) => trigger.parentNode"
									v-model:value="record.warehouseId"
									placeholder="请选择仓库"
								>
									<a-select-option v-for="item in warehouseinfoList" :key="item.value" :value="item.value">{{
										item.label
									}}</a-select-option>
								</a-select>
							</template>

							<template v-if="column.dataIndex === 'remark'">
								<a-input :disabled="props.disabled" :style="{ width: column.width }" v-model:value="record.remark" />
							</template>
						</template>
					</a-table>
				</a-col>
			</a-row>

			<div style="margin-top: 15px">
				<span style="color: #333; font-size: 16px; font-weight: 600">合计</span>
			</div>
			<a-row :gutter="24" style="margin-bottom: 50px; margin-top: 15px; margin-left: 20px">
				<a-col :span="8">
					<div style="margin-right: 12px; display: inline-block">
						<span>销售数量:</span>
					</div>
					<a-input style="width: 50%; border-radius: 5px" disabled placeholder="0" v-model:value="saleNum" />
				</a-col>
				<a-col :span="8">
					<div style="margin-right: 12px; display: inline-block">
						<span>含税总金额</span>
					</div>
					<a-input style="width: 50%; border-radius: 5px" disabled placeholder="0" v-model:value="taxAmount" />
				</a-col>
				<a-col :span="8">
					<div style="margin-right: 12px; display: inline-block">
						<span>不含税总金额</span>
					</div>
					<a-input style="width: 50%; border-radius: 5px" disabled placeholder="0" v-model:value="noTaxAmount" />
				</a-col>
			</a-row>
		</a-form>
		<system :value="{}"></system>
		<productSelector
			:data-provider="getOrderDetailList"
			:columns="selectorColumns"
			@onProductChange="onProductChange"
			ref="productsRef"
		/>
		<user-selector-plus
			ref="userSelectorPlusRef"
			:org-tree-api="selectorApiFunction.orgTreeApi"
			:user-page-api="selectorApiFunction.userPageApi"
			:checked-user-list-api="selectorApiFunction.checkedUserListApi"
			:data-is-converter-flw="true"
			@onBack="selectUserCallback"
		/>
	</div>
</template>

<script setup name="dbsForm">
	import { required } from '@/utils/formRules'
	import productSelector from '@/components/Selector/productSelector.vue'
	import customerApi from '@/api/base_data/customerApi'
	import { message } from 'ant-design-vue'
	import { toRaw, onMounted } from 'vue'
	import revenueContractApi from '@/api/contract/revenueContract/index'
	import UserSelectorPlus from '@/components/Selector/userSelectorPlus.vue'
	import orgApi from '@/api/sys/orgApi'
	import userCenterApi from '@/api/sys/userCenterApi'
	import xnPageSelector from '@/components/XnPageSelect/index.vue'
	import tool from '@/utils/tool'
	import system from '@/components/Task/system.vue'

	// 定义emit事件
	//PROCUREMENT_PARTNERS
	const emit = defineEmits({ successful: null })
	const productsRef = ref()
	const formRef = ref()
	const revenueContractRef = ref()
	const customerRef = ref()
	let orderDetailAddParamList = []

	// 表单数据，也就是默认给一些数据
	const formData = ref({})
	const saleNum = ref(0)
	const taxAmount = ref(0)
	const noTaxAmount = ref(0)
	const userSelectorPlusRef = ref()
	const warehouseinfoList = ref([])
	const selectorApiFunction = {
		orgTreeApi: (param) => {
			return orgApi.orgOrgTreeSelector(param).then((data) => {
				return Promise.resolve(data)
			})
		},
		userPageApi: (param) => {
			return orgApi.orgUserSelector(param).then((data) => {
				return Promise.resolve(data)
			})
		},
		checkedUserListApi: (param) => {
			return userCenterApi.userCenterGetUserListByIdList(param).then((data) => {
				return Promise.resolve(data)
			})
		}
	}
	const onContractChange = (id, item) => {
		let detailList = item.productList || []
		detailList.forEach((it) => {
			it['key'] = it['productId']
			it['id'] = it['productId']
		})
		orderDetailAddParamList = [].concat(detailList)
		formData.value.saleOrderDetailAddParamList = detailList
		taxAmount.value = totalTax()
		noTaxAmount.value = totalExcludingTaxTax()
		saleNum.value = totalOrderNum()
	}

	const selectionParticipants = () => {
		if (props.disabled) {
			return
		}
		let data = []
		if (formData.value.salePerId) {
			data.push({
				key: 'USER',
				label: formData.value.salePerName,
				value: formData.value.salePerId
			})
		}
		userSelectorPlusRef.value.showUserPlusModal(data)
	}

	const selectUserCallback = (value) => {
		formData.value.salePerId = value.value
		formData.value.salePerName = value.label
	}

	onMounted(() => {
		nextTick(() => {
			revenueContractRef.value.onPage({})
			customerRef.value.onPage({})
		})
	})

	const options = {
		rowSelection: {
			onChange: (selectedRowKey, selectedRows) => {
				selectedRowKeys.value = selectedRowKey
			}
		}
	}

	const removeGoods = () => {
		let datas = formData.value.saleOrderDetailAddParamList
		selectedRowKeys.value.forEach((element) => {
			let index = datas.findIndex((it) => {
				return it['key'] == element
			})
			if (index >= 0) {
				datas.splice(index, 1)
			}
		})
		selectedRowKeys.value = []
		taxAmount.value = totalTax()
		noTaxAmount.value = totalExcludingTaxTax()
		saleNum.value = totalOrderNum()
	}
	const selectedRowKeys = ref([])

	const formatPrice = (text) => {
		let value = text.match(/^\d*(\.?\d{0,2})/g)[0] || null
		if (isNaN(value)) {
			return ''
		}
		return value
	}

	const taxChange = (record) => {
		record.taxPrice = formatPrice(record.taxPrice)
		taxAmount.value = totalTax()
	}

	const excludingTaxChange = (record) => {
		record.noTaxPrice = formatPrice(record.noTaxPrice)
		noTaxAmount.value = totalExcludingTaxTax()
	}

	const orderNumChange = (record) => {
		let value = record.saleNum.replace(/[^\d]+/g, '')
		if (isNaN(value)) {
			record.saleNum = ''
		} else {
			record.saleNum = value
		}
		saleNum.value = totalOrderNum()
	}

	const taxRateChange = (record) => {
		let value = record.taxRate.replace(/[^\d]+/g, '')
		if (isNaN(value)) {
			record.taxRate = ''
		} else {
			record.taxRate = value
		}
	}
	const totalExcludingTaxTax = () => {
		let orderList = formData.value.saleOrderDetailAddParamList || []
		let amount = 0
		orderList.forEach((it) => {
			let noTaxPrice = it['noTaxPrice']
			if (noTaxPrice) {
				amount += parseFloat(noTaxPrice)
			}
		})
		return amount.toFixed(2).replace('.00', '')
	}
	const totalTax = () => {
		let orderList = formData.value.saleOrderDetailAddParamList || []
		let amount = 0
		orderList.forEach((it) => {
			let taxPrice = it['taxPrice']
			if (taxPrice) {
				amount += parseFloat(taxPrice)
			}
		})
		return amount.toFixed(2).replace('.00', '')
	}

	const totalOrderNum = () => {
		let orderList = formData.value.saleOrderDetailAddParamList || []
		let amount = 0
		orderList.forEach((it) => {
			let orderNum = it['saleNum']
			if (orderNum) {
				amount += parseInt(orderNum)
			}
		})
		return amount
	}

	const props = defineProps({
		value: {
			type: Object,
			default: () => {}
		},
		disabled: {
			type: Boolean,
			default: () => false
		}
	})
	watch(
		() => props.value,
		(newVal, oldVal) => {
			if (newVal) {
				console.log(newVal)
				formData.value = { ...newVal }
				console.log(newVal.proSaleOrderDetailList)
				if(newVal.proSaleOrderDetailList){
					formData.value.saleOrderDetailAddParamList =[].concat(newVal.proSaleOrderDetailList)
				}
			}
		},
		{ deep: true, immediate: true }
	)

	const onProductChange = (items) => {
		let saleOrderDetailAddParamList = formData.value.saleOrderDetailAddParamList || []
		items.forEach((it) => {
			let find = saleOrderDetailAddParamList.find((item) => {
				return item['productId'] == it['productId']
			})
			if (find) {
				it = Object.assign(it, find)
			}
		})
		formData.value.saleOrderDetailAddParamList = items
	}

	const selectorColumns = [
		{
			title: '序号',
			dataIndex: 'index',
			ellipsis: true,
			width: 80,
			align: 'center'
		},
		{
			title: '产品编号',
			width: 100,
			dataIndex: 'productCode',
			align: 'center',
			ellipsis: true
		},
		{
			title: '产品名称',
			width: 120,
			dataIndex: 'productName',
			align: 'center',
			ellipsis: true
		},
		{
			title: '品牌',
			width: 100,
			dataIndex: 'productUnit',
			align: 'center',
			ellipsis: true
		},
		{
			title: '规格',
			width: 100,
			dataIndex: 'productSpec',
			align: 'center',
			ellipsis: true
		},
		{
			title: '商品单价',
			width: 100,
			dataIndex: 'unitPrice',
			align: 'center',
			ellipsis: true
		}
	]

	// 默认要校验的
	const formRules = {
		saleMethod: [required('请选择销售方式')],
		contractId: [required('请选择合同')],
		customerId: [required('请选择客户')],
		settleMethod: [required('请选择结算方式')],
		salePerName: [required('请选择销售员')]
	}
	const addProduct = () => {
		if (!formData.value.contractId) {
			message.error('请选择合同')
			return
		}
		if (!formData.value.saleOrderDetailAddParamList) {
			formData.value.saleOrderDetailAddParamList = []
		}
		productsRef.value.showDialog(formData.value.saleOrderDetailAddParamList)
	}
	// 验证并提交数据
	const getData = () => {
		return new Promise((resolve, reject) => {
			submitApi()
				.then((data) => {
					resolve(data)
				})
				.catch((error) => {
					let msg = error.message
					if (msg) {
						message.error(msg)
					}
				})
		})
	}

	const validatedField = (orderList) => {
		if (orderList.length <= 0) {
			return '请添加商品'
		}
		let msg = null
		let itemRules = [
			{
				field: 'saleNum',
				error: '销售数量不能为空!'
			}
		]
		for (let i = 0; i < orderList.length; i++) {
			for (let rule of itemRules) {
				let item = orderList[i]
				let itemValue = item[rule['field']]
				if (!itemValue) {
					msg = `第${i + 1}行${rule['error']}`
					break
				}
			}
		}
		return msg
	}

	const submitApi = () => {
		return new Promise((resolve, reject) => {
			formRef.value
				.validate()
				.then(() => {
					let orderList = toRaw(formData.value.saleOrderDetailAddParamList) || []
					let msg = validatedField(orderList)
					if (msg) {
						reject(new Error(msg))
					} else {
						let params = { ...formData.value }
						let products = [].concat(orderList)
						params['flowCode'] = 'FLW_SALE_ORDER'
						if (formData.id) {
							params.saleOrderDetailEditParamList = products
						} else {
							params.saleOrderDetailAddParamList = products
						}
						Object.assign(params, {
							type: '销售',
							saleNum: saleNum.value,
							taxAmount: taxAmount.value,
							noTaxAmount: noTaxAmount.value
						})
						console.log(JSON.stringify(params))
						resolve(params)
					}
				})
				.catch((e) => reject(e))
		})
	}
	// 重置
	const resetForm = () => {
		formRef.value.resetFields()
	}
	// 调用这个函数将子组件的一些数据和方法暴露出去
	defineExpose({
		getData,
		resetForm
	})

	const getOrderDetailList = (parameter) => {
		console.log(orderDetailAddParamList)
		return Promise.resolve({
			records: orderDetailAddParamList,
			total: orderDetailAddParamList.length,
			current: 1,
			pages: 10
		}).then((res) => {
			return res
		})
	}

	const goodsColumns = [
		{
			title: '序号',
			width: 80,
			dataIndex: 'index',
			align: 'center'
		},
		{
			title: '产品编号',
			width: 120,
			dataIndex: 'productCode',
			align: 'center',
			ellipsis: true
		},
		{
			title: '产品名称',
			dataIndex: 'productName',
			width: 180,
			align: 'center',
			ellipsis: true
		},
		{
			title: '单位',
			dataIndex: 'productUnit',
			width: 100,
			align: 'center'
		},
		{
			title: '规格型号',
			dataIndex: 'productSpec',
			width: 120,
			align: 'center'
		},
		{
			title: '税率',
			dataIndex: 'tax',
			width: 120,
			align: 'center'
		},
		{
			title: '销售数量',
			dataIndex: 'saleNum',
			width: 120,
			align: 'center'
		},
		{
			title: '含税金额',
			dataIndex: 'taxPrice',
			width: 120,
			align: 'center'
		},
		{
			title: '不含税金额',
			dataIndex: 'noTaxPrice',
			width: 140,
			align: 'center'
		},
		{
			title: '备注',
			dataIndex: 'remark',
			width: 200,
			align: 'center'
		}
	]
</script>

<style scoped :type="less">
	.childAddButton {
		margin-bottom: 10px;
	}
</style>
